﻿using QRCoder;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace ST.Common.Util.Drawing
{
	public class ImageHelper
	{
		/// <summary>
		/// 自定义图片大小
		/// </summary>
		/// <param name="inputPath">原图路径</param>
		/// <param name="outputPath">输出路径</param>
		/// <param name="maxWidth">最大宽度，图片原始宽度大于设置宽度时等比例缩放</param>
		/// <param name="maxHeight">最大高度，图片原始高度大于设置高度时等比例缩放</param>
		/// <param name="format"></param>
		/// <param name="quality">范围：0~100</param>
		/// <returns></returns>
		public static bool Resize(string inputPath, string outputPath, int maxWidth, int maxHeight, ImageFormat format, int? quality)
		{
			try
			{
				int width, height;
				#region reckon size 
				using (Image current = Image.FromFile(inputPath))
				{
					if (maxHeight < current.Height || maxWidth < current.Width)
					{
						if (current.Width > current.Height)
						{
							width = maxWidth;
							height = Convert.ToInt32(current.Height * maxWidth / (double)current.Width);
						}
						else
						{
							width = Convert.ToInt32(current.Width * maxHeight / (double)current.Height);
							height = maxHeight;
						}
					}
					else
					{
						width = current.Width;
						height = current.Height;
					}

					#endregion

					#region get resized bitmap 
					var canvas = new Bitmap(width, height);

					using (var graphics = Graphics.FromImage(canvas))
					{
						graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
						//graphics.SmoothingMode = SmoothingMode.HighSpeed;
						graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;//InterpolationMode.HighQualityBicubic
						graphics.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;

						graphics.DrawImage(current, 0, 0, width, height);
					}
					#endregion

					if (quality.HasValue && format == ImageFormat.Jpeg)
					{
						ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
						ImageCodecInfo codecInfo = null;
						for (int x = 0; x < arrayICI.Length; x++)
						{
							if (arrayICI[x].FormatID == format.Guid)
							{
								codecInfo = arrayICI[x];
								break;
							}
						}

						if (codecInfo != null)
						{
							EncoderParameters ep = new EncoderParameters(1);
							ep.Param[0] = new EncoderParameter(Encoder.Quality, new long[] { quality.Value });//设置压缩的比例1-100

							canvas.Save(outputPath, codecInfo, ep);
						}
						else
						{
							canvas.Save(outputPath, format);
						}
					}
					else
					{
						canvas.Save(outputPath, format);
					}
				}
				return true;
			}
			catch (Exception ex)
			{
				return false;
			}
		}
	}
}
